﻿using Core.Framework.EntityExtend.AiExpression;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Reflection;

namespace Core.Framework.EntityExtend.Model
{
    /// <summary>
    /// EFCore实体映射关系
    /// [泛型缓存]
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class EFCoreModel<T> where T: class,new()
    {
        /// <summary>
        /// 缓存内容
        /// </summary>
        private static Mapping<T> mapping { get; set; }

        /// <summary>
        /// 映射关系
        /// </summary>
        /// <returns></returns>
        public static Mapping<T> GetModelMapping()
        {
            if (mapping == null)
            {

                mapping = new Mapping<T>();

                var type = typeof(T);

                // 获取TableName 名称
                mapping.tableName 
                    = type.IsDefined(typeof(TableAttribute), true) ?
                        ((TableAttribute)type.GetCustomAttribute(typeof(TableAttribute))).Name 
                        : type.Name;

                mapping.tableName 
                    = string.IsNullOrWhiteSpace(mapping.tableName) ? type.Name : mapping.tableName;

                // 获取字段名
                foreach (var item in typeof(T).GetProperties())
                {

                    var filedParameter = new FiledParameter();

                    filedParameter.name = type.IsDefined(typeof(ColumnAttribute), true) ?
                        ((ColumnAttribute)type.GetCustomAttribute(typeof(ColumnAttribute))).Name
                        : item.Name;

                    //filedParameter.isIdentity = true;

                    filedParameter.name 
                        = string.IsNullOrWhiteSpace(filedParameter.name) ? type.Name : filedParameter.name;

                    mapping.rows.Add(item.Name, filedParameter);
                }

            }

            return mapping;
        }
    }

    /// <summary>
    /// 映射关系
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Mapping<T> where T : class
    {
        /// <summary>
        /// 表明
        /// </summary>
        public string tableName { get; set; }

        /// <summary>
        /// 字段和表对应关系
        /// </summary>
        public Dictionary<string, FiledParameter> rows { get; set; } 
            = new Dictionary<string, FiledParameter>();
    }
}
